package cn.lbd.kill.server.service;

import cn.lbd.kill.server.dto.MailDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.MailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Arrays;

@Service
@Transactional
@EnableAsync
public class MailService {
    @Autowired
    private JavaMailSenderImpl mailSender;
    @Autowired
    private Environment environment;

    @Async
    public void sendEmail(final MailDTO mailDTO) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        //发送者
        helper.setFrom(environment.getProperty("mail.send.from"));
        //标题
        helper.setSubject(mailDTO.getSubject());
        //收件人
        System.out.println("<===========================>"+Arrays.toString(mailDTO.getTos()));
        helper.setTo(mailDTO.getTos());
        //内容
        helper.setText(mailDTO.getContents(),true);
        mailSender.send(mimeMessage);
    }
}
